package com.sh.gateway.controller;

import com.google.common.collect.Maps;
import com.sh.gateway.common.JsonMapper;
import com.sh.gateway.common.ResultUtil;
import com.sh.gateway.entity.PermissionMenu;
import com.sh.gateway.entity.Role;
import com.sh.gateway.entity.User;
import com.sh.gateway.enums.ResultEnum;
import com.sh.gateway.handle.ExceptionHandle;
import com.sh.gateway.service.PermissionMenuServcie;
import com.sh.gateway.service.RoleService;
import com.sh.gateway.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author: he changjie on 2019/01/18
 * @Description:
 */
@RestController
@RequestMapping("/authentication")
public class AuthenticationController {

    private JsonMapper jsonMapper = JsonMapper.INSTANCE;
    @Autowired
    private ExceptionHandle exceptionHandle;
    @Autowired
    private PermissionMenuServcie menuService;
    @Autowired
    private RoleService roleService;
    @Autowired
    private UserService userService;

    /**
     * 添加一项权限菜单
     * @param menu
     * @return
     */
    @RequestMapping(value = "/menu/add",method = RequestMethod.POST)
    public ResponseEntity addMenu(@RequestBody PermissionMenu menu){
        try {
            int add = menuService.add(menu);
            if(add!=-1){
                return new ResponseEntity(ResultUtil.success(null), HttpStatus.OK);
            }else{
                return new ResponseEntity(ResultUtil.error(ResultEnum._FAILED), HttpStatus.OK);
            }
        } catch (Exception e) {
            return new ResponseEntity(exceptionHandle.exceptionGet(e), HttpStatus.OK);
        }
    }

    /**
     * 通过主键查询权限菜单
     * @param id 权限菜单ID
     * @return
     */
    @RequestMapping(value = "/menu/queryOne/{id}",method = RequestMethod.GET)
    public ResponseEntity queryOneMenu(@PathVariable String id){
        try {
            PermissionMenu menu = menuService.queryOne(id);
            if(menu!=null){
                return new ResponseEntity(ResultUtil.success(menu), HttpStatus.OK);
            }else{
                return new ResponseEntity(ResultUtil.error(ResultEnum._FAILED), HttpStatus.OK);
            }
        } catch (Exception e) {
            return new ResponseEntity(exceptionHandle.exceptionGet(e), HttpStatus.OK);
        }
    }

    /**
     * 修改一项权限菜单
     * @param menu
     * @return
     */
    @RequestMapping(value = "/menu/update",method = RequestMethod.POST)
    public ResponseEntity updateMenu(@RequestBody PermissionMenu menu){
        try {
            int add = menuService.update(menu);
            if(add!=-1){
                return new ResponseEntity(ResultUtil.success(null), HttpStatus.OK);
            }else{
                return new ResponseEntity(ResultUtil.error(ResultEnum._FAILED), HttpStatus.OK);
            }
        } catch (Exception e) {
            return new ResponseEntity(exceptionHandle.exceptionGet(e), HttpStatus.OK);
        }
    }

    /**
     * 删除一项权限菜单
     * 级联将含有该项权限的角色移除该项权限
     * @param id
     * @return
     */
    @RequestMapping(value = "/menu/delete/{id}",method = RequestMethod.GET)
    public ResponseEntity deleteMenu(@PathVariable String id){
        try {
            int add = menuService.delete(id);
            if(add!=-1){
                return new ResponseEntity(ResultUtil.success(null), HttpStatus.OK);
            }else{
                return new ResponseEntity(ResultUtil.error(ResultEnum._FAILED), HttpStatus.OK);
            }
        } catch (Exception e) {
            return new ResponseEntity(exceptionHandle.exceptionGet(e), HttpStatus.OK);
        }
    }

    /**
     * 分页
     * 拉取所有权限菜单
     * @return
     */
    @RequestMapping(value = "/menu/queryAll/{params}",method = RequestMethod.GET)
    public ResponseEntity queryAllMenu(@PathVariable String params){
        try {
            Map fromJson = jsonMapper.fromJson(params, Map.class);
            String search = (String)fromJson.get("search");
            int currentPage = (int)fromJson.get("currentPage");
            int pageSize = (int)fromJson.get("pageSize");
            List<PermissionMenu> list = menuService.queryAll(search,currentPage,pageSize);
            if(list!=null){
                HashMap<String, Object> map = Maps.newHashMap();
                map.put("list",list);
                map.put("total",menuService.queryAll(search));
                map.put("currentPage",currentPage);
                map.put("pageSize",pageSize);
                return new ResponseEntity(ResultUtil.success(map), HttpStatus.OK);
            }else{
                return new ResponseEntity(ResultUtil.error(ResultEnum._FAILED), HttpStatus.OK);
            }
        } catch (Exception e) {
            return new ResponseEntity(exceptionHandle.exceptionGet(e), HttpStatus.OK);
        }
    }

    /**
     * 根据权限等级拉取权限菜单
     * @param level 权限等级
     * @return
     */
    @RequestMapping(value = "/menu/queryAllByLevel/{level}",method = RequestMethod.GET)
    public ResponseEntity queryAllByLevelMenu(@PathVariable String level){
        try {
            List<PermissionMenu> menus = menuService.queryAllByLevel(level);
            if(menus!=null){
                return new ResponseEntity(ResultUtil.success(menus), HttpStatus.OK);
            }else{
                return new ResponseEntity(ResultUtil.error(ResultEnum._FAILED), HttpStatus.OK);
            }
        } catch (Exception e) {
            return new ResponseEntity(exceptionHandle.exceptionGet(e), HttpStatus.OK);
        }
    }

    /**
     * 通过主键查询角色
     * @param id 角色ID
     * @return
     */
    @RequestMapping(value = "/role/queryOne/{id}",method = RequestMethod.GET)
    public ResponseEntity queryOneRole(@PathVariable String id){
        try {
            Role role = roleService.queryOne(id);
            if(role!=null){
                return new ResponseEntity(ResultUtil.success(role), HttpStatus.OK);
            }else{
                return new ResponseEntity(ResultUtil.error(ResultEnum._FAILED), HttpStatus.OK);
            }
        } catch (Exception e) {
            return new ResponseEntity(exceptionHandle.exceptionGet(e), HttpStatus.OK);
        }
    }

    /**
     * 添加一名角色
     * @param role 角色
     * @return
     */
    @RequestMapping(value = "/role/add",method = RequestMethod.POST)
    public ResponseEntity addRole(@RequestBody Role role){
        try {
            int add = roleService.add(role);
            if(add!=-1){
                return new ResponseEntity(ResultUtil.success(null), HttpStatus.OK);
            }else{
                return new ResponseEntity(ResultUtil.error(ResultEnum._FAILED), HttpStatus.OK);
            }
        } catch (Exception e) {
            return new ResponseEntity(exceptionHandle.exceptionGet(e), HttpStatus.OK);
        }
    }

    /**
     * 更新一名角色的名称或权限
     * 该角色有集合中的权限则略过，无则添加，多则删除
     * @param params 请求参数（id角色ID、name名称、menus权限菜单集合（以,间隔））
     * @return
     */
    @RequestMapping(value = "/role/update",method = RequestMethod.POST)
    public ResponseEntity updateRole(@RequestBody String params){
        try {
            Map fromJson = jsonMapper.fromJson(params, Map.class);
            String id = (String) fromJson.get("id");
            String name = (String) fromJson.get("roleName");
            String menus = (String) fromJson.get("menus");
            int update = roleService.update(id, name, menus);
            if(update!=-1){
                return new ResponseEntity(ResultUtil.success(null), HttpStatus.OK);
            }else{
                return new ResponseEntity(ResultUtil.error(ResultEnum._FAILED), HttpStatus.OK);
            }
        } catch (Exception e) {
            return new ResponseEntity(exceptionHandle.exceptionGet(e), HttpStatus.OK);
        }
    }

    /**
     * 删除一名角色
     * 级联将为该角色的用户的角色至为null;
     * @param id
     * @return
     */
    @RequestMapping(value = "/role/delete/{id}",method = RequestMethod.GET)
    public ResponseEntity deleteRole(@PathVariable String id){
        try {
            int add = roleService.delete(id);
            if(add!=-1){
                return new ResponseEntity(ResultUtil.success(null), HttpStatus.OK);
            }else{
                return new ResponseEntity(ResultUtil.error(ResultEnum._FAILED), HttpStatus.OK);
            }
        } catch (Exception e) {
            return new ResponseEntity(exceptionHandle.exceptionGet(e), HttpStatus.OK);
        }
    }

    /**
     * 分页
     * 拉取所有角色列表
     * @return
     */
    @RequestMapping(value = "/role/queryAll/{params}",method = RequestMethod.GET)
    public ResponseEntity queryAll(@PathVariable String params){
        try {
            Map fromJson = jsonMapper.fromJson(params, Map.class);
            String search = (String)fromJson.get("search");
            int currentPage = (int)fromJson.get("currentPage");
            int pageSize = (int)fromJson.get("pageSize");
            List<Object> list = roleService.queryAll(search,currentPage,pageSize);
            if(list!=null){
                HashMap<String, Object> map = Maps.newHashMap();
                map.put("list",list);
                map.put("total",roleService.queryAll(search));
                map.put("currentPage",currentPage);
                map.put("pageSize",pageSize);
                return new ResponseEntity(ResultUtil.success(map), HttpStatus.OK);
            }else{
                return new ResponseEntity(ResultUtil.error(ResultEnum._FAILED), HttpStatus.OK);
            }
        } catch (Exception e) {
            return new ResponseEntity(exceptionHandle.exceptionGet(e), HttpStatus.OK);
        }
    }

    /**
     * 通过角色ID查询所属权限列表
     * @param roleId 角色ID
     * @return
     */
    @RequestMapping(value = "/role/queryAllByRoleId/{roleId}",method = RequestMethod.GET)
    public ResponseEntity queryAllByRoleId(@PathVariable String roleId){
        try {
            List<PermissionMenu> menus = roleService.queryAllByRoleId(roleId);
            if(menus!=null){
                return new ResponseEntity(ResultUtil.success(menus), HttpStatus.OK);
            }else{
                return new ResponseEntity(ResultUtil.error(ResultEnum._FAILED), HttpStatus.OK);
            }
        } catch (Exception e) {
            return new ResponseEntity(exceptionHandle.exceptionGet(e), HttpStatus.OK);
        }
    }

    @RequestMapping(value = "/login",method = RequestMethod.POST)
    public ResponseEntity login(@RequestBody User user){
        try {
            User login = userService.login(user);
            if(login!=null){
                List<PermissionMenu> menus = roleService.queryAllByRoleId(login.getRoleId());
                HashMap<String, Object> map = Maps.newHashMap();
                map.put("menus",menus);
                map.put("nickname",login.getNickname());
                map.put("userId",login.getId());
                return new ResponseEntity(ResultUtil.success(map), HttpStatus.OK);
            }else{
                return new ResponseEntity(ResultUtil.error(ResultEnum._FAILED), HttpStatus.OK);
            }
        } catch (Exception e) {
            return new ResponseEntity(exceptionHandle.exceptionGet(e), HttpStatus.OK);
        }
    }

    /**
     * 添加用户
     * @param user 用户
     * @return
     */
    @RequestMapping(value = "/user/add",method = RequestMethod.POST)
    public ResponseEntity addUser(@RequestBody User user){
        try {
            int add = userService.add(user);
            if(add!=-1){
                return new ResponseEntity(ResultUtil.success(null), HttpStatus.OK);
            }else{
                return new ResponseEntity(ResultUtil.error(ResultEnum._FAILED), HttpStatus.OK);
            }
        } catch (Exception e) {
            return new ResponseEntity(exceptionHandle.exceptionGet(e), HttpStatus.OK);
        }
    }

    /**
     * 更新用户信息
     * @param user 用户
     * @return
     */
    @RequestMapping(value = "/user/update",method = RequestMethod.POST)
    public ResponseEntity updateUser(@RequestBody User user){
        try {
            int add = userService.update(user);
            if(add!=-1){
                return new ResponseEntity(ResultUtil.success(null), HttpStatus.OK);
            }else{
                return new ResponseEntity(ResultUtil.error(ResultEnum._FAILED), HttpStatus.OK);
            }
        } catch (Exception e) {
            return new ResponseEntity(exceptionHandle.exceptionGet(e), HttpStatus.OK);
        }
    }

    /**
     * 用户修改密码
     * @param id 用户ID
     * @param pwd 新密码
     * @param opwd 原密码
     * @return
     */
    @RequestMapping(value = "/user/updatepwd/{id}/{opwd}/{pwd}",method = RequestMethod.GET)
    public ResponseEntity updatePwdUser(@PathVariable String id,@PathVariable String opwd,@PathVariable String pwd){
        try {
            int add = userService.updatePWD(id,pwd,opwd);
            if(add!=-1){
                return new ResponseEntity(ResultUtil.success(null), HttpStatus.OK);
            }else{
                return new ResponseEntity(ResultUtil.error(ResultEnum._FAILED), HttpStatus.OK);
            }
        } catch (Exception e) {
            return new ResponseEntity(exceptionHandle.exceptionGet(e), HttpStatus.OK);
        }
    }

    /**
     * 通过ID查询用户
     * @param id id用户ID
     * @return
     */
    @RequestMapping(value = "/user/queryOne/{id}",method = RequestMethod.GET)
    public ResponseEntity queryOneUser(@PathVariable String id){
        try {
            User user = userService.queryOne(id);
            if(user!=null){
                return new ResponseEntity(ResultUtil.success(user), HttpStatus.OK);
            }else{
                return new ResponseEntity(ResultUtil.error(ResultEnum._FAILED), HttpStatus.OK);
            }
        } catch (Exception e) {
            return new ResponseEntity(exceptionHandle.exceptionGet(e), HttpStatus.OK);
        }
    }

    /**
     * 删除用户
     * @param id 用户ID
     * @return
     */
    @RequestMapping(value = "/user/delete/{id}",method = RequestMethod.GET)
    public ResponseEntity deleteUser(@PathVariable String id){
        try {
            int add = userService.delete(id);
            if(add!=-1){
                return new ResponseEntity(ResultUtil.success(null), HttpStatus.OK);
            }else{
                return new ResponseEntity(ResultUtil.error(ResultEnum._FAILED), HttpStatus.OK);
            }
        } catch (Exception e) {
            return new ResponseEntity(exceptionHandle.exceptionGet(e), HttpStatus.OK);
        }
    }

    /**
     * 分页
     * 拉取所有用户信息列表
     * @return ResponseEntity
     */
    @RequestMapping(value = "/user/queryAll/{params}",method = RequestMethod.GET)
    public ResponseEntity queryAllUser(@PathVariable String params){
        try {
            Map fromJson = jsonMapper.fromJson(params, Map.class);
            String search = (String)fromJson.get("search");
            int currentPage = (int)fromJson.get("currentPage");
            int pageSize = (int)fromJson.get("pageSize");
            List<User> users = userService.queryAll(search,currentPage,pageSize);
            if(users!=null){
                HashMap<String, Object> map = Maps.newHashMap();
                map.put("list",users);
                map.put("total",userService.queryAll(search));
                map.put("currentPage",currentPage);
                map.put("pageSize",pageSize);
                return new ResponseEntity(ResultUtil.success(map), HttpStatus.OK);
            }else{
                return new ResponseEntity(ResultUtil.error(ResultEnum._FAILED), HttpStatus.OK);
            }
        } catch (Exception e) {
            return new ResponseEntity(exceptionHandle.exceptionGet(e), HttpStatus.OK);
        }
    }

    /**
     * 返回除了自己的所有用户的ID和昵称
     * @return List<Object>
     * @return ResponseEntity
     */
    @RequestMapping(value = "/user/queryS/{id}",method = RequestMethod.GET)
    public ResponseEntity queryS(@PathVariable String id){
        try {
            List<Object> objects = userService.queryS(id);
            if(objects!=null){
                return new ResponseEntity(ResultUtil.success(objects), HttpStatus.OK);
            }else{
                return new ResponseEntity(ResultUtil.error(ResultEnum._FAILED), HttpStatus.OK);
            }
        } catch (Exception e) {
            return new ResponseEntity(exceptionHandle.exceptionGet(e), HttpStatus.OK);
        }
    }

}
